package com.sais.manage.boot.platform.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 宿舍管理系统-二维码 controller
 *
 * @author zhang
 * @date 2020/02/25
 **/
@Api(tags = "二维码管理")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/platform/kap")
public class KapController {


    @Autowired
    private DefaultKaptcha kaptcha;

    @ApiOperation("随机生成 验证码")
    @RequestMapping(value = "create/{num}",method = RequestMethod.GET)
    public void getKapImage(@PathVariable("num") String num,
                                HttpServletRequest request,
                                HttpServletResponse response){
        HttpSession session = request.getSession();
        //设置失效时间 立即失效 无缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");

        //返回值类型
        response.setContentType("image/ipeg");

        //生成验证码
        String text = kaptcha.createText();

        //将验证码保存session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY,text);

        //生成图片
        BufferedImage image = kaptcha.createImage(text);

        //以流形式返回到response
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
